package com.gx.controller;

import com.gx.aspect.annotation.OperationLogger;
import com.gx.domain.SysRole;
import com.gx.page.TableDataInfo;
import com.gx.response.R;
import com.gx.service.api.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/roles")
public class RoleController extends BaseController {

    @Autowired
    private SysRoleService sysRoleService;

    @GetMapping
    public R list(@RequestParam(value = "name", defaultValue = "", required = false) String name, @RequestParam(value = "remark", defaultValue = "", required = false) String remark) {
        startPage();
        List<SysRole> sysRoles = sysRoleService.queryListLike(name, remark);
        TableDataInfo dataTable = getDataTable(sysRoles);
        return R.ok().put("rows", dataTable.getRows()).put("total", dataTable.getTotal());
    }

    @OperationLogger(option = "批量删除角色")
    @DeleteMapping("/batch")
    public R batchDelete(@RequestParam("ids") String ids) {
        List<Long> collect = Arrays.stream(ids.split(",")).mapToLong(id -> Long.parseLong(id)).boxed().collect(Collectors.toList());
        int batchDelete = sysRoleService.batchDelete(collect);
        return R.ok("删除成功");
    }

    @OperationLogger(option = "添加角色")
    @PostMapping
    public R add(@RequestBody SysRole sysRole) {
        SysRole checkRole = sysRoleService.queryByName(sysRole.getName());
        if (checkRole != null) {
            return R.error("该角色已存在，请勿重复添加");
        }

        sysRoleService.save(sysRole);
        return R.ok("新增成功");
    }

    @OperationLogger(option = "修改角色")
    @PutMapping
    public R update(@RequestBody SysRole sysRole, @RequestParam("ids") String ids) {
        // 角色对应菜单idList
        List<Long> menuIds = Arrays.stream(ids.split(",")).mapToLong(id -> Long.parseLong(id)).boxed().collect(Collectors.toList());
        sysRoleService.update(sysRole, menuIds);
        return R.ok("更新成功");
    }

}
